package com.tencent.examples.core.processor.itop;

import com.alibaba.fastjson.JSONObject;
import com.tencent.bk.utils.blueking.properties.ItopProperties;
import com.tencent.bk.utils.blueking.tools.HttpsClient;
import com.tencent.examples.core.processor.BlueKingProcessor;
import com.tencent.examples.core.processor.MessageProcessor;
import com.tencent.examples.core.processor.common.BkobjidEnum;
import com.tencent.examples.core.processor.dto.BkItopInstDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author :  CHENWEN
 * @Description : ITOP消息
 * @Creation Date:  2019/3/30
 */
@Component
public class ItopConnect {
    @Autowired
    ItopProperties itopProperties;
    @Autowired
    MessageProcessor messageProcessor;
    @Autowired
    BlueKingProcessor blueKingProcessor;

    /**
     * 每天凌晨12点拉取数据
     */
    @SuppressWarnings("unchecked")
    @Scheduled(cron = "0 0 0 * * ?")
    public void conn() {
        String url = itopProperties.getUrl();

        JSONObject j = new JSONObject();
        j.put("operation", "core/get");
        j.put("class", "Location");
        j.put("key", "SELECT Location");

        List<BkItopInstDto> bkJkInstDtos = blueKingProcessor.jkSearchProcessor(BkobjidEnum.itop);
        if (bkJkInstDtos == null || bkJkInstDtos.size() <= 0) {
            return;
        }

        StringBuilder output_fields = new StringBuilder();
        for (BkItopInstDto bkJkInstDto : bkJkInstDtos) {
            output_fields.append(bkJkInstDto.getItop()).append(",");
        }
        j.put("output_fields", output_fields.toString().substring(0, output_fields.toString().length() - 1));

        url = url + "&json_data=" + j.toJSONString();

        HashMap<String, String> head = new HashMap<>();
        head.put("Cookie", "itop-7da515443a82fcacf15d74c766f4b34b=" + itopProperties.getToken());

        JSONObject result;
        try {
            result = HttpsClient.httpRequest(url.replaceAll("\"", "%22").replaceAll(" ", "%20"), "GET", null, head);
            if (result != null) {
                JSONObject jsonObject = result.getJSONObject("objects");
                jsonObject.forEach((key, value) -> {
                    JSONObject syncData = ((JSONObject) value).getJSONObject("fields");
                    messageProcessor.syncStore(BkobjidEnum.itop, syncData, 0);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
